package WebTools::IP;
use strict;
use warnings;
use utf8;

use base qw/WebCore/;
use Data::FormValidator::Constraints qw(ip_address);
use Encode;
use Tools::IPCheck;


sub home:Default {
    my $this = shift;

    #取得客户端得IP
    my $your_ip = &get_ip();
    my $your_place = &check_ip($your_ip, $this->cfg('ip_db'));

    #取得用户传入的IP地址
    #验证表单
    my ($check_ip, $check_place);
    if ( $this->query->param('ip') ) {
        my $check_form_result = $this->check_rm('_ip_form_validate',
            '_ip_form_profile')
            || return $this->check_rm_error_page;

        $check_ip = $check_form_result->valid('ip');
        $check_place = &check_ip($check_ip, $this->cfg('ip_db'));
        my ($main_data, $sub_data) = &check_ip_from_ip138($check_ip);

        $this->set_tt_var('check_ip', $check_ip);
        $this->set_tt_var('check_place', $check_place);
        $this->set_tt_var('main_ip_data', $main_data);
        $this->set_tt_var('sub_ip_data', $sub_data);
        
    }



    #设置变量
    $this->set_tt_var('your_ip', $your_ip);
    $this->set_tt_var('your_place', $your_place);
    $this->set_tt_var('customer_title', 'IP地址查询 - 5anet.com');
    return $this->process_template('ip.tt2');

}


#IP表单验证
#如果表单验证失败
sub _ip_form_validate {
    my $this = shift;
    my $errs = shift;
    
    foreach my $key ( keys %$errs ) {
        $this->set_tt_var($key, $errs->{$key});
    }

    #取得客户端得IP
    my $your_ip = &get_ip();
    my $your_place = &check_ip($your_ip, $this->cfg('ip_db'));
    $this->set_tt_var('your_ip', $your_ip);
    $this->set_tt_var('your_place', $your_place);
    $this->set_tt_var('customer_title', 'IP地址查询 - 5anet.com');

    return $this->process_template('ip.tt2');
}


#IP表单验证profile
sub _ip_form_profile {
    my $this = shift;

    return  {
        required=>'ip',

        constraint_methods=>{
            ip=>ip_address(),
        },

        msgs=>{
            constraints=>{
                ip_address=>'IP地址格式不合法',
            },
        },
    };
}



1;
